#!/usr/bin/env node
"use strict";

require("./util/prototype.js");
const fileUtil = require("./util/fileUtil");
const ejsFilePath = process.mainModule.filename.replace(
    "bin\\myCmd.js",
    "lib\\ejs\\json.ejs"
);

module.exports = function(workFolder, fileName, encoding, fileOutputPath) {
    fileUtil
        .readFilePromise(workFolder + "/" + fileName, encoding)
        .then(content => {
            // 匹配所有数字
            const regex = /(\/\*\*[^\/]+\/)*\s+private\s+(\w+)\s+(\w+)\s*;/gu;
            const regexLabel = /\*\s*(.+)\s*/gmu;

            let data = [];
            let item = [];
            while (item != null) {
                item = regex.exec(content);
                if (item != null) {
                    let prop = item[3];
                    let label = "";
                    if (item[1] !== undefined) {
                        label = item[1]
                            .match(regexLabel)[1]
                            .replace("*", "")
                            .replace("\r\n", "")
                            .trim();
                    }

                    data.push({ prop, label });
                }
            }

            fileUtil
                .renderFilePromise(ejsFilePath, { data })
                .then(str => {
                    if (fileOutputPath) {
                        fileUtil
                            .writeFilePromise(str, fileOutputPath, encoding)
                            .then(filePath => {
                                console.log(`${filePath}已保存`);
                            });
                    } else {
                        console.log(str);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        });
};
